package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.pojo.dto.FormDataRepeatDTO;
import com.xbongbong.paas.pojo.vo.CheckRepeatVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.model.CompetitorAnalysisModel;
import com.xbongbong.saas.model.CompetitorModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author: yingjf
 * @date: 2022/8/31 10:41
 * @description:
 */
@Component
@Slf4j
public class CompetitorHelp {

    @Resource
    private CompetitorModel competitorModel;

    @Resource
    private CompetitorAnalysisModel competitorAnalysisModel;

    /**
     * 解析竞争对手两个字段，机会使用，不让存隐藏字段，需要特殊解析
     * date: 2022/8/31 1:46 下午
     * @author yingjf
     * @param corpid:公司id
     * @param data:机会data
     */
    public void analysisCompetior(String corpid, JSONObject data){
        try {
            Object winCompetitorIdObject = data.get(SalesOpportunityEnum.WIN_COMPETITOR.getAttr());
            JSONArray jsonArray = data.getJSONArray(SalesOpportunityEnum.LINK_COMPETITOR.getAttr());
            if(winCompetitorIdObject==null&& CollectionsUtil.isEmpty(jsonArray)){
                return;
            }
            Set<Long> set = new HashSet<>();
            boolean needDealLinkCompetitor = false;
            if(CollectionsUtil.isNotEmpty(jsonArray)){
                needDealLinkCompetitor = true;
                jsonArray.forEach(item->{
                    if(item instanceof Number){
                        set.add(Long.parseLong(item.toString()));
                    }
                });
            }
            if(set.size()>0){
                needDealLinkCompetitor = true;
            }
            boolean needDealWinCompetitor = false;
            Long winCompetitorId = null;
            if(winCompetitorIdObject!=null){
                if(winCompetitorIdObject instanceof Number){
                    needDealWinCompetitor = true;
                    winCompetitorId = Long.parseLong(winCompetitorIdObject.toString());
                    set.add(winCompetitorId);
                }

            }
            if(CollectionsUtil.isNotEmpty(set)){
                List<CompetitorEntity> competitorEntityList = competitorModel.getByKeys(set, corpid);
                Map<Long,CompetitorEntity> competitorEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                competitorEntityList.forEach(item->{
                    competitorEntityMap.put(item.getId(),item);
                });
                if(needDealWinCompetitor){
                    CompetitorEntity competitorEntity = competitorEntityMap.get(winCompetitorId);
                    String name = competitorEntity.getData().getString(CompetitorEnum.NAME.getAttr());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id",winCompetitorId);
                    jsonObject.put("name",name);
                    jsonObject.put("businessType",XbbRefTypeEnum.COMPETITOR.getCode());
                    JSONArray tempJsonArray = new JSONArray();
                    tempJsonArray.add(jsonObject);
                    data.put(SalesOpportunityEnum.WIN_COMPETITOR.getAttr(),tempJsonArray);
                }
                if(needDealLinkCompetitor){
                    JSONArray nameArray = new JSONArray();
                    for(Object item:jsonArray){
                        long id = Long.parseLong(item.toString());
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id",id);
                        jsonObject.put("name",competitorEntityMap.get(id).getData().getString(CompetitorEnum.NAME.getAttr()));
                        jsonObject.put("businessType", XbbRefTypeEnum.COMPETITOR.getCode());
                        nameArray.add(jsonObject);
                    }
                    data.put(SalesOpportunityEnum.LINK_COMPETITOR.getAttr(),nameArray);
                }
            }
        }catch (Exception e){
            log.error("机会解析竞争对手字段出错：",e);
        }

    }

    /**
     * 解析赢单竞争对手，不让存隐藏字段，需要特殊解析
     * date: 2022/8/25 4:02 下午
     * @author yingjf
     * com.xbongbong.saas.help.FormDataAnalysisHelp#analysisWinCompetior
     */
    public void analysisWinCompetior(String corpid, JSONObject data){
        Object object = data.get(SalesOpportunityEnum.WIN_COMPETITOR.getAttr());
        if(object!=null){
            long id = Long.parseLong(object.toString());
            CompetitorEntity competitorEntity = competitorModel.getByKey(id, corpid);
            String name = competitorEntity.getData().getString(CompetitorEnum.NAME.getAttr());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",id);
            jsonObject.put("name",name);
            jsonObject.put("businessType",XbbRefTypeEnum.COMPETITOR.getCode());
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            data.put(SalesOpportunityEnum.WIN_COMPETITOR.getAttr(),jsonArray);
        }
    }

    /**
     * 解析关联竞争对手，不让存隐藏字段，需要特殊解析
     * date: 2022/8/31 10:43 上午
     * @author yingjf
     * com.xbongbong.saas.help.FormDataAnalysisHelp#analysisWinCompetior
     */
    public void analysisLinkCompetior(String corpid,JSONObject data){
        JSONArray jsonArray = data.getJSONArray(SalesOpportunityEnum.LINK_COMPETITOR.getAttr());
        if(jsonArray!=null){
            Set<Long> idSet = new HashSet<>();
            for(Object item:jsonArray){
                long id = Long.parseLong(item.toString());
                idSet.add(id);
            }
            List<CompetitorEntity> competitorEntityList = competitorModel.getByKeys(idSet, corpid);
            Map<Long,String> nameMap =  new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            competitorEntityList.forEach(item->{
                nameMap.put(item.getId(),item.getData().getString(CompetitorEnum.NAME.getAttr()));
            });
            JSONArray nameArray = new JSONArray();
            for(Object item:jsonArray){
                long id = Long.parseLong(item.toString());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id",id);
                jsonObject.put("name",nameMap.get(id));
                jsonObject.put("businessType", XbbRefTypeEnum.COMPETITOR.getCode());
                nameArray.add(jsonObject);
            }
            data.put(SalesOpportunityEnum.LINK_COMPETITOR.getAttr(),nameArray);
        }
    }

    /**
     * 导出解析竞争对手，不让存隐藏字段，需要特殊解析
     * date: 2022/9/5 4:27 下午
     * @author yingjf
     * @param corpid:
     * @param paasFormDataESList:
     */
    public void analysisCompetior4Export(String corpid, List<PaasFormDataEntityExt> paasFormDataESList){
        Set<Long> idSet = new HashSet<>();
        paasFormDataESList.forEach(item->{
            JSONObject data = item.getData();
            JSONArray linkCompetitorIdjsonArray = data.getJSONArray(SalesOpportunityEnum.LINK_COMPETITOR.getAttr());
            if(linkCompetitorIdjsonArray!=null){
                for(Object o:linkCompetitorIdjsonArray){
                    long id = Long.parseLong(o.toString());
                    idSet.add(id);
                }
            }
            Object winCompetitorIdjsonArray = data.get(SalesOpportunityEnum.WIN_COMPETITOR.getAttr());
            if(winCompetitorIdjsonArray!=null){
                long id = Long.parseLong(winCompetitorIdjsonArray.toString());
                idSet.add(id);
            }
        });
        if(idSet.size()>0){
            Map<Long,String> nameMap = new HashMap<>(idSet.size());
            List<CompetitorEntity> competitorEntityList = competitorModel.getByKeys(idSet, corpid);
            competitorEntityList.forEach(item->{
                String name = item.getData().getString(CompetitorEnum.NAME.getAttr());
                nameMap.put(item.getId(),name);
            });
            paasFormDataESList.forEach(item->{
                JSONObject data = item.getData();
                JSONArray linkCompetitorIdjsonArray = data.getJSONArray(SalesOpportunityEnum.LINK_COMPETITOR.getAttr());
                List<String> nameList = new ArrayList<>();
                if(linkCompetitorIdjsonArray!=null){
                    for(Object o:linkCompetitorIdjsonArray){
                        long id = Long.parseLong(o.toString());
                        nameList.add(nameMap.get(id));
                    }
                }
                String nameStr = StringUtils.join(nameList, StringConstant.COMMA);
                data.put(SalesOpportunityEnum.LINK_COMPETITOR.getAttr(),nameStr);

                Object winCompetitorIdjsonArray = data.get(SalesOpportunityEnum.WIN_COMPETITOR.getAttr());
                if(winCompetitorIdjsonArray!=null){
                    long id = Long.parseLong(winCompetitorIdjsonArray.toString());
                    data.put(SalesOpportunityEnum.WIN_COMPETITOR.getAttr(),nameMap.get(id));
                }

            });
        }
    }

    /**
     * 关联业务单选
     * 将前端传入的json对象格式转换成两个字段
     * date: 2022/8/25 3:15 下午
     * @author yingjf
     * @param data: 前端传回的data数据
     */
    public static void formatWinCompetitorLinkBusiness4Save(JSONObject data) throws XbbException {
        try {
            String attr = SalesOpportunityEnum.WIN_COMPETITOR.getAttr();
            JSONArray jsonArray = data.getJSONArray(attr);
            if (jsonArray != null) {
                if(jsonArray.isEmpty()){
                    data.put(attr, null);
                    return;
                }
                List<Long> idList = new ArrayList<>();
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                // 存的是long
                idList.add(jsonObject.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                if(idList.size() > BasicConstant.ZERO) {
                    data.put(attr, idList.get(BasicConstant.ZERO));
                }else {
                    data.put(attr, null);
                }
                data.put(SalesOpportunityEnum.WIN_COMPETITOR_LINK_TEXT.getAttr(),
                        jsonObject.getString(StringConstant.SAAS_LINK_BUSINESS_NAME));
            } else {
                //data.put(attr, null);
            }
        } catch (Exception e) {
            //   throw new XbbException(ErrorCodeEnum.API_ERROR_100015);
        }
    }

    /**
     * 判断是否重复  目前只有文本字段
     * date: 2022/9/16 1:57 下午
     * @author yingjf
     * @param formDataRepeatDTO:
     */
    public CheckRepeatVO repeat(FormDataRepeatDTO formDataRepeatDTO) throws XbbException {
        CheckRepeatVO checkRepeatVO = new CheckRepeatVO();
        checkRepeatVO.setNoRepeat(true);
        try {
            String attr = formDataRepeatDTO.getAttr();
            Object value = formDataRepeatDTO.getValue();
            String corpid = formDataRepeatDTO.getCorpid();
            Long dataId = formDataRepeatDTO.getDataId();
            Boolean isEmpty = formDataRepeatDTO.getValue() == null || StringUtil.isEmpty(formDataRepeatDTO.getValue().toString());
            if (isEmpty) {
                return checkRepeatVO;
            }
            Long repeat = competitorAnalysisModel.repeat(corpid, dataId,attr, value.toString());
            checkRepeatVO.setNoRepeat(repeat>0?false:true);
        }catch (Exception e){
            log.error("com.xbongbong.saas.help.CompetitorHelp.repeat",e);
        }
        return checkRepeatVO;
    }

}
